/*
 * Project: SmartWard
 * Package: com.ruoyi.ichen.app.service
 * File: ProfileUploadAndDownService
 * Date: 2020-2-16 23:17
 * Version: V1.0
 * Copyright © 2018 - 2019 YESOFT CHINA, Inc. All Rights Reserved.
 */
package com.ruoyi.ichen.app.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.ichen.base.configs.AliyunConfig;
import com.ruoyi.project.system.user.entity.User;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName: ProfileUploadAndDownService
 * @Description: 文件上传阿里oss,
 * @Author chenhuanghua
 * @Date 2020-2-16 23:17
 * @Version V1.0
 */
@Service
public class ProfileUploadAndDownService {

    @Autowired
    AliyunConfig aliyunConfig;

    public String upload(MultipartFile file, String[] allowedExtension) {

        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        try {
            //是否是图片的文件和上传的大小
            FileUploadUtils.assertAllowed(file, allowedExtension);

            // 地域节点
            String endpoint = aliyunConfig.getEndpoint();
            // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
            String accessKeyId = aliyunConfig.getAccessKeyId();
            String accessKeySecret = aliyunConfig.getAccessKeySecret();
            // BucketName
            String yourBucketName = aliyunConfig.getBucketName();
            // 在文件名称之前添加uuid值，保证文件名称不重复
            String uuid = UUID.randomUUID().toString();
            String fileName = FileUploadUtils.extractFilename(file);
            // 获取当前日期 2020/01/03
            String filePath = new DateTime().toString("yyyy/MM/dd");
            // 拼接文件完整路径 2020/01/03/parker.jpg
            fileName = filePath + "/" + fileName;
            // 获取上传文件输入流
            InputStream in = file.getInputStream();
            // 3.把上传文件存储到阿里云oss里面
            // 创建OSSClient实例。
            OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流
            // 第一个参数时BucketName，第二个参数是文件名称，第三个参数是输入流
            ossClient.putObject(yourBucketName, fileName, in);
            // 关闭OSSClient。
            ossClient.shutdown();
            // 返回上传之后的oss存储路径
            String path = "http://" + yourBucketName + "." + endpoint + "/" + fileName;
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}